<template>
  <div class="tag-container">
    <!-- 绑定表单引用和验证规则 -->
    <el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
      <el-form-item label="标签名称" prop="newTag">
        <el-input
          v-model="form.newTag"
          placeholder="请输入标签名称"
          @keyup.enter="onSubmit"
          style="width: 300px; margin-right: 20px"
        />
      </el-form-item>
      <el-form-item label="英文昵称" prop="en_name">
        <el-input
          v-model="form.en_name"
          placeholder="请输入英文昵称"
          @keyup.enter="onSubmit"
          style="width: 300px; margin-right: 20px"
        />
      </el-form-item>
      <!-- 新增描述输入框 -->
      <el-form-item label="描述">
        <el-input
          v-model="form.description"
          placeholder="请输入标签描述（可选）"
          style="width: 300px; margin-right: 20px"
        />
      </el-form-item>
    </el-form>
    <div class="button">
      <!-- 修改点击事件，触发 close 事件 -->
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineProps, watch } from 'vue';
import { createTag, updateTag } from '@/api/tag';
import { getUserName } from '@/utils/auth';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['submit', 'close']);
const props = defineProps<{
  editData?: {
    id: number;
    name: string;
    en_name: string;
    description: string;
  };
}>();

// 定义表单引用
const formRef = ref(null);
// 更新表单数据，添加 description 字段
const form = ref({
  newTag: '',
  description: '',
  en_name: '',
});

// 监听编辑数据变化，更新表单
watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      form.value.newTag = newVal.name;
      form.value.description = newVal.description;
      form.value.en_name = newVal.en_name || '';
    }
  },
  { immediate: true },
);

// 定义表单验证规则
const rules = {
  newTag: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
  en_name: [
    { required: true, message: '请输入英文昵称', trigger: 'blur' },
    { pattern: /^[a-zA-Z_]+$/, message: '英文昵称只能包含英文字母和下划线', trigger: 'blur' },
  ],
};

const onSubmit = async () => {
  if (!formRef.value) return;
  try {
    // 验证表单
    await formRef.value.validate();
    const data: any = {
      name: form.value.newTag,
      // 使用用户输入的 description 值
      description: form.value.description,
      en_name: form.value.en_name,
      creator: getUserName(),
    };
    if (props.editData) {
      data['id'] = props.editData.id;
      const res = await updateTag(data);
      if (res.data.code === 200) {
        ElMessage.success('标签编辑成功');
      }
    } else {
      const res = await createTag(data);
      if (res.data.code === 200) {
        ElMessage.success('标签创建成功');
      }
    }
    // 表单提交成功，重置表单
    formRef.value.resetFields();
    emit('submit'); // 触发父组件的提交事件
  } catch (error) {
    console.error('表单验证失败', error);
  }
};

const onReset = () => {
  if (formRef.value) {
    // 重置表单
    formRef.value.resetFields();
  }
};

// 新增关闭方法，触发 close 事件
const onClose = () => {
  emit('close');
};
</script>

<style lang="scss" scoped>
.tag-container {
  padding: 20px;
}

.tag-list {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.button {
  display: flex;
  justify-content: flex-end;
}
</style>
